/*
 * Copyright 2010 - 2011, The PLDesktop Development Team
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

#include "initrdmodulehandler.h"

#include <plconfig.h>
#include <elf/plelf.h>

InitRDModuleHandler::InitRDModuleHandler() {
    m_modules = new PLRadixTree<InitRDModuleInfo *>();
}

InitRDModuleInfo *InitRDModuleHandler::loadModule(TarFile *moduleFile) {
    InitRDModuleInfo *module = new InitRDModuleInfo(moduleFile);
    m_modules->insert(moduleFile->filename(), module);
    PLElf *elf = new PLElf();
    module->setElf(elf);
    uint8_t *data = (uint8_t *)moduleFile->startPosition();
    PLElfBase::ElfCreateError error = elf->create(data, moduleFile->fileSize());
    if(!elf->relocate(data, moduleFile->fileSize())) {
        printf("Error relocating %s ELF header.", moduleFile->filename());
    }
//    uintptr_t start = elf->lookup("module_init");
//    printf("Init: %x ", (uint8_t *)moduleFile->startPosition() + start);
//    void (*fp)(void) = reinterpret_cast<void (*)(void)>(*((uint8_t *)moduleFile->startPosition() + start));
//    fp();
    return module;
}
